<template>
    <jb-page
        title-text="字典管理"
        title-icon="fluent-mdl2:dictionary"
        conditions-align="start"
    >
        <template #conditions>
            <jb-btn
                icon="mdi:database-refresh"
                type="info"
                confirm-text="确认对字典数据重新检测并进行初始化吗？"
                url="/api/admin/dictionary/checkAndInit"
                @success="typePage?.loadData()"
                >检测并初始化</jb-btn
            >
        </template>
        <template #opt>
            <span class="text-16px">数据项：</span>
            <span class="text-16px color-error">{{ currentType?.name ?? '未选' }}</span>
        </template>
        <splitpanes class="h-full default-theme">
            <pane size="60">
                <jb-crud-page
                    ref="typePage"
                    conditions-align="end"
                    :bordered="true"
                    search-url="/api/admin/dictionaryType/datas"
                    :search-conditions="typePageConditions"
                    :edit-component="TypeEdit"
                    edit-modal-width="500"
                    @after-search="currentType = null"
                >
                    <template #title>
                        <span class="text-16px">类型</span>
                    </template>
                    <template #conditions-form>
                        <jb-select
                            v-model:value="typePageConditions.enable"
                            url="/api/admin/dictionary/options?typeKey=options_enable"
                            placeholder="=是否启用="
                            class="w-130px"
                            :clearable="false"
                            filterable
                        ></jb-select>
                        <n-input
                            v-model:value="typePageConditions.keywords"
                            placeholder="关键词检索 名称、KEY"
                        ></n-input>
                    </template>
                    <template #opt>
                        <jb-btn
                            tip-text="添加新数据分类"
                            quaternary
                            circle
                            :icon="Icons.ADD"
                            type="primary"
                            @click="typePage?.showEditModal('新增数据分类')"
                        ></jb-btn>
                    </template>

                    <template #default="{ state }">
                        <jb-table
                            :start-index="state.tableStartIndex"
                            :data="state.list"
                            @cell-click="onTypeClick"
                        >
                            <jb-column
                                type="seq"
                                title="序号"
                                width="60"
                                fixed="left"
                            ></jb-column>
                            <jb-column
                                field="name"
                                title="名称"
                                min-width="200"
                                fixed="left"
                            ></jb-column>
                            <jb-column
                                field="typeKey"
                                title="标识KEY"
                                min-width="200"
                            ></jb-column>
                            <jb-column field="modeLevel" title="模式层级" width="100">
                                <template #default="{ row }">
                                    {{ row?.modeLevel == 1 ? '一' : '多' }}级
                                </template>
                            </jb-column>
                            <jb-column field="enable" title="是否启用" width="80">
                                <template #default="{ row }">
                                    <jb-switch
                                        v-if="row.isBuildIn == false"
                                        v-model:value="row.enable"
                                        confirm="切换后此类型下的所有字典数据与类型启用状态更新一致，确定切换此字典类型启用状态？"
                                        :url="`/api/admin/dictionaryType/toggleEnable/${row.id}`"
                                        @change="typePage?.loadData()"
                                    ></jb-switch>
                                </template>
                            </jb-column>
                            <jb-column title="操作" width="110" fixed="right">
                                <template #default="{ row }">
                                    <jb-btn
                                        v-if="row.isBuildIn == false"
                                        tip-text="编辑"
                                        :icon="Icons.EDIT"
                                        size="small"
                                        type="warning"
                                        secondary
                                        quaternary
                                        circle
                                        strong
                                        @click="
                                            typePage?.showEditModal('编辑数据分类', {
                                                id: row.id
                                            })
                                        "
                                    ></jb-btn>
                                    <jb-btn
                                        v-if="row.isBuildIn == false"
                                        tip-text="删除"
                                        size="small"
                                        confirm-text="确认删除该分类吗？"
                                        :url="`/api/admin/dictionaryType/delete/${row.id}`"
                                        :icon="Icons.DELETE"
                                        type="error"
                                        quaternary
                                        circle
                                        strong
                                        secondary
                                        class="mx-8px"
                                        @success="typePage?.loadData()"
                                    ></jb-btn>
                                </template>
                            </jb-column>
                        </jb-table>
                    </template>
                </jb-crud-page>
            </pane>
            <pane size="40">
                <jb-crud-page
                    ref="itemPage"
                    :bordered="true"
                    :pager="false"
                    search-url="/api/admin/dictionary/datas"
                    :search-conditions="itemPageConditions"
                    :edit-component="ItemEdit"
                    :reset-btn-shown="false"
                    @after-render="expandItemTree()"
                >
                    <template #title> </template>
                    <template #conditions-form>
                        <jb-select
                            v-model:value="itemPageConditions.enable"
                            url="/api/admin/dictionary/options?typeKey=options_enable"
                            placeholder="=是否启用="
                            :clearable="false"
                            filterable
                            class="w-130px"
                        ></jb-select>
                        <n-input
                            v-model:value="itemPageConditions.keywords"
                            placeholder="关键词检索 名称、编号"
                        ></n-input>
                    </template>
                    <template #opt>
                        <jb-btn
                            v-if="currentType"
                            tip-text="新增此分类下数据项"
                            :icon="Icons.ADD"
                            type="primary"
                            quaternary
                            circle
                            @click="
                                itemPage?.showEditModal(
                                    `新增[${currentType.name}]下数据项`,
                                    {
                                        typeId: currentType.id,
                                        isMultiLevel: currentType.modeLevel != 1
                                    }
                                )
                            "
                        ></jb-btn>
                        <jb-btn
                            v-if="currentType"
                            tip-text="开启排序"
                            :icon="Icons.DRAG"
                            :quaternary="!dragable"
                            type="info"
                            circle
                            @click="dragable = !dragable"
                        ></jb-btn>
                        <jb-btn
                            v-if="currentType"
                            tip-text="清空此分类下所有数据项"
                            confirm-text="确认清空此分类下所有数据项吗？"
                            :icon="Icons.DELETE"
                            quaternary
                            :url="`/api/admin/dictionary/clearByType/${currentType?.id}`"
                            type="error"
                            circle
                            class="mx-8px"
                            @success="itemPage?.loadData()"
                        ></jb-btn>
                    </template>

                    <template #default="{ list }">
                        <jb-table
                            ref="itemTableRef"
                            :tree-config="{
                                childrenField: 'items',
                                reserve: true,
                                expandAll: true,
                                rowField: 'id'
                            }"
                            :column-config="{ useKey: true }"
                            :data="list"
                            :dragable="dragable"
                            rank-field="sortRank"
                            @drag-end="handleDragEnd"
                        >
                            <jb-column
                                field="name"
                                title="名称"
                                align="left"
                                header-align="center"
                                tree-node
                                min-width="160"
                                fixed="left"
                            ></jb-column>
                            <jb-column
                                field="sn"
                                title="编号(SN)"
                                min-width="160"
                            ></jb-column>
                            <jb-column field="enable" title="是否启用" width="80">
                                <template #default="{ row }">
                                    <jb-switch
                                        v-model:value="row.enable"
                                        :url="`/api/admin/dictionary/toggleEnable/${row.id}`"
                                        @change="itemPage?.loadData()"
                                    ></jb-switch>
                                </template>
                            </jb-column>
                            <jb-column title="操作" width="110" fixed="right">
                                <template #default="{ row }">
                                    <jb-btn
                                        v-if="row.isBuildIn == false"
                                        tip-text="编辑"
                                        size="small"
                                        :icon="Icons.EDIT"
                                        type="warning"
                                        secondary
                                        circle
                                        @click="
                                            itemPage?.showEditModal(`修改数据项`, {
                                                id: row.id,
                                                typeId: currentType?.id,
                                                isMultiLevel: currentType?.modeLevel != 1
                                            })
                                        "
                                    ></jb-btn>
                                    <jb-btn
                                        v-if="row.isBuildIn == false"
                                        tip-text="删除"
                                        size="small"
                                        :icon="Icons.DELETE"
                                        confirm-text="确认删除此数据吗？"
                                        :url="`/api/admin/dictionary/delete/${row.id}`"
                                        type="error"
                                        class="mx-8px"
                                        secondary
                                        circle
                                        @success="itemPage?.loadData()"
                                    ></jb-btn>
                                </template>
                            </jb-column>
                        </jb-table>
                    </template>
                </jb-crud-page>
            </pane>
        </splitpanes>
    </jb-page>
</template>
<script setup lang="ts">
import { nextTick, reactive, ref, watch } from 'vue'
import { type VxeTableInstance } from 'vxe-table'
import { Icons } from '@/constants'
import { JBoltApi } from '@/utils'
import JbCrudPage from '@/components/_builtin/jb-crud-page/index.vue'
import { useResetableData } from '@/hooks/common/use-resetable-data'
import { Model } from '@/typings/api'
import { DragEndEventArgs } from '@/typings/jbolt.components'
import TypeEdit from './components/type-edit/index.vue'
import ItemEdit from './components/item-edit/index.vue'

/*     类型相关 start  */
const typePage = ref<InstanceType<typeof JbCrudPage> | null>(null)
const typePageConditions = useResetableData({
    //查询条件
    keywords: '',
    enable: 'true'
})
const currentType = ref<Model | null>(null)
function onTypeClick({ row }: { row: Model }) {
    currentType.value = row
}
/*     类型相关 end  */

/** 拖拽排序相关 start */
const dragable = ref(false)
function handleDragEnd(data: DragEndEventArgs) {
    return JBoltApi.post('/api/admin/dictionary/changeSortRank', {
        id: data.id,
        oriPid: data.oriPid,
        oriRank: data.oriRank,
        newPid: data.newPid,
        newRank: data.newRank
    }).then(() => {
        return itemPage.value?.loadData()
    })
}

/** 拖拽排序相关 end */

/*     数据项相关 start  */
watch(
    () => currentType.value,
    (type) => {
        itemPageConditions.typeId = (type?.id ?? '') as string
        itemPage.value?.loadData()
    }
)
const itemPage = ref<InstanceType<typeof JbCrudPage> | null>(null)
const itemTableRef = ref<VxeTableInstance<Model>>()
const itemPageConditions = reactive({
    //查询条件
    keywords: '',
    enable: 'true',
    typeId: ''
})
function expandItemTree() {
    nextTick(() => {
        itemTableRef.value?.setAllTreeExpand(true)
    })
}
/*     数据项相关 end  */
</script>

<style scoped></style>
